<?php
namespace Home\Controller;
class WechatController extends BaseController {
	
	public function checkToken(){
    	if (!isset($_GET["echostr"])) {
    	    $create_menu_url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$this->getToken();
	        $createMenu='{
    "button": [
        {
            "type": "view", 
            "name": "E职课", 
            "url": "http://m.91eshixi.com/index.php?s=/index/courseIn"
        }, 
        {
            "type": "view", 
            "name": "我的E课", 
            "url": "http://m.91eshixi.com/index.php?s=/index/mycourseIn"
        }, 
        {
            "name": "E实习", 
            "sub_button": [
                {
                    "type": "view", 
                    "name": "关于E实习", 
                    "url": "http://www.soso.com/"
                }, 
                {
                    "type": "view", 
                    "name": "名企实习", 
                    "url": "http://www.soso.com/"
                }
            ]
        }
    ]
}';
	       // $result = $this->request_post($create_menu_url,$createMenu);
	        //响应事件
	       $this->responseMsg();
    	}else {
    	    //验证token
	    	$echoStr = $_GET["echostr"];
	        if($this->checkSignature()){
	        	echo $echoStr;exit;
	        }
    	}
    }
    //微信接入
	public function checkSignature(){
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];

		$token = C("token");
		$tmpArr = array($token, $timestamp, $nonce);
        // use SORT_STRING rule
		sort($tmpArr, SORT_STRING);
		$tmpStr = implode( $tmpArr );
		$tmpStr = sha1( $tmpStr );
		
		if( $tmpStr == $signature ){
			return true;
		}else{
			return false;
		}
	}
	//获取自定义菜单
	public function getJsonMenu(){
	    header("Content-Type: text/html;charset=utf-8");
	    $menu=M("custom_menu")->order('sort asc')->select();
	    $menu=D('Tree')->toTree($menu);
	    $set = array();
	    $set['button'] = array();
	    foreach ($menu as $key=>$value){
	        $entry = array();
	        $entry['name'] = $value['title'];
	        if(empty($value['_child'])){
	                 $entry['type']=$value['type'];
	            if($value['type']=='view'){
	                $entry['url']=$value['url'];
	            }else{
	                $entry['key']=$value['keyword'];
	            }
	            /* $entry['type']=$value['type'];
	            $entry['url']=$value['url']; */
	        }else{
	            foreach ($value['_child'] as $k=>$v){
	                $e = array();
	                $e['type'] = $v['type'];
	                $e['name'] = $v['title'];
	                //跳转路径
	                if($v['type']== 'view'){
	                    $e['url'] =  $v['url'];
	                    //触发关键字
	                }else{
	                    $e['key'] = $v['keyword'];
	                }
	                $entry['sub_button'][] = $e;
	            }
	        }
	        $set['button'][] = $entry;
	    }
	    $dat =json_encode($set);
	    $dat = $this->dotrans($dat);
	    return $dat;
	}
	
	//格式化路径
	private function dotrans($code) {
	    return preg_replace("#\\\u([0-9a-f]+)#ie", "iconv('UCS-2BE', 'utf-8', pack('H4', '\\1'))",$code);
	}
	 
    /**
     * 清空菜单
     * @author 碎月无晴 <906857431@qq.com>
     */
     public function clearMenu(){
         $account=M("member_public")->find();
         $APPID=$account['appid'];
         $APPSECRET=$account['secret'];
         $TOKEN_URL="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$APPID."&secret=".$APPSECRET;
         $json=file_get_contents($TOKEN_URL);
         $result=json_decode($json);
         $ACC_TOKEN=$result->access_token;
         $delUrl="https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=".$ACC_TOKEN;
         $result=D("member_public")->request_get($delUrl);
         $result =json_decode($result, true);
         $result=$result['errcode'];
         if($result==0){
             $this->success('清空成功',U('Reply/menuList'));
         }else{
             $this->error('清空失败！');
         }
         
     }
	
     
    
    /**
     * 响应消息
     */
    public function responseMsg(){
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; 
        if (!empty($postStr)){
            libxml_disable_entity_loader(true);
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $ERENT_TYPE = trim($postObj->MsgType);
            switch ($ERENT_TYPE){
                //事件
                case "event":
                    $result = $this->receiveEvent($postObj);
                    break;
                    //文本
                case "text":
                    $result = $this->receiveText($postObj);
                    break;
                    //图片
                case "image":
                    $result = $this->receiveImage($postObj);
                    break;
                    //位置
                case "location":
                    $result = $this->transmitText($object, "这是一个位置信息");
                    break;
                    //录音
                case "voice":
                    $result = $this->transmitText($object, "这是一个录音信息");
                    break;
                    //视频
                case "video":
                    $result = $this->transmitText($object, "这是一个视频信息");
                    break;
                case "link":
                    $result = $this->transmitText($object, "这是一个链接信息");
                    break;
                default:
                    $result = "unknown msg type: ".$ERENT_TYPE;
                    break;
            }
            echo $result;
            }else {
                echo "欢迎关注E实习";
                exit;
            }  
      }
    /**
     * 接收事件消息
     */
    public function receiveEvent($object){
        $content = "";
        $responseType="text";
        switch ($object->Event)
        {
            case "subscribe":
               //$responseType="subscribe";
              // $object->Content="subscribe";
                $content="Hi，你终于来了,E实习是国内首家公益性的基于知识分享的大学生职业发展学习与职业实践体验服务平台!“更好的课程、更好的实习”是我们的承诺与使命 。 从“E”出发，让我们一起创造同学们的精彩职业人生";
               $openid=$object->FromUserName;
                break;
            case "unsubscribe":
                $openid = $object->FromUserName;
                break;
            case "SCAN":
                $content = "扫描场景 ".$object->EventKey;
                break;
            case "CLICK":
                switch ($object->EventKey)
                {
                    case "COMPANY":
                        $content = "";
                        break;
                    default:
                        $openid= $object->FromUserName;
                        $responseType="other";
                        $object->Content=$object->EventKey;
                        break;
                }
                break;
            case "LOCATION":
                $content = "上传位置：纬度 ".$object->Latitude.";经度 ".$object->Longitude;
                return $result;
                break;
            case "VIEW":
                $openid=strval($object->FromUserName);
                $content = "跳转链接 ".$object->EventKey;
                break;
            default:
                $content = "receive a new event: ".$object->Event;
                break;
        }
        //发送文本消息
        if($responseType=="text"){
            $result = $this->transmitText($object, $content);
            return $result;
        //触发文本回复
        }else{
            $result=$this->receiveText($object);
            return $result;
        }
    }
     /**
      * 文本文字触发事件
      * @param   $object
      * @return  
      */
     public  function receiveText($object){
         $Content=$object->Content;
        if($Content=="subscribe"){
             //触发关注回复
             $title="为什么要用易卡系统？打开了解我们";
             $desc="了解易卡，了解一款帮你赚钱的收银系统";
             $link="http://mp.weixin.qq.com/s?__biz=MzIwOTM3Mjk4Nw==&mid=100000060&idx=1&sn=933396b0dbdf64cc2f19f51b0366f85c&scene=0&previewkey=B%2FR4rwNMvCyHLa61rUF8pswqSljwj2bfCUaCyDofEow%3D#wechat_redirect";
             $picurl="https://mmbiz.qlogo.cn/mmbiz/EBDJbGICTUr4nCYXF6ibgsbmM2PCs18jaymYNq7chozvTwjuN3XIwHYoWlTYN6Rt7QIg1Unm8pgxZUickezbRHbg/0?wx_fmt=jpeg";
             $newsArray=array(
                 'Title'=>$title,
                 'Description'=>$desc,
                 'PicUrl'=>$picurl,
                 'Url'=>"http:www.baidu.com"
             );
             $result=$this->transmitImageInfo($object,$newsArray);
            echo $result;
         }else{
             $content="欢迎关注E实习!";
             $result =$this->transmitText($object,$content);
             return $result;
         }  
    }
    /**
     * 图片消息触发事件
     */
     public  function receiveImage($object){
        $imageArray['MediaId']=trim($object->MediaId);
        $mediaid=strval($object->MediaId);
        $result = $this->transmitImage($object, $imageArray);
        return $result;
    }
    /**
     * 发送文本消息
     * @param   $object
     * @param   $content
     * @return  
     */
    public  function transmitText($object, $content){
        $textTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[text]]></MsgType>
                    <Content><![CDATA[%s]]></Content>
                    </xml>";
        $result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content);
        return $result;
    }
    
    /**
     * 回复图片消息
     */
    public function transmitImage($object, $imageArray){
        $itemTpl = "<Image>
                        <MediaId><![CDATA[%s]]></MediaId>
                    </Image>";
        $item_str = sprintf($itemTpl, $imageArray['MediaId']);
        $textTpl = "<xml>
        <ToUserName><![CDATA[%s]]></ToUserName>
        <FromUserName><![CDATA[%s]]></FromUserName>
        <CreateTime>%s</CreateTime>
        <MsgType><![CDATA[image]]></MsgType>
        $item_str
        </xml>";
        $result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }
    /**
     * 发送图文消息
     * @param unknown $object
     * @param unknown $newsArray
     * @return string|unknown
     */
    public function transmitImageInfo($object,$newsArray){
          if(!is_array($newsArray)){
              return "";
          }
        $itemTpl = " <item>
                            <Title><![CDATA[%s]]></Title>
                            <Description><![CDATA[%s]]></Description>
                            <PicUrl><![CDATA[%s]]></PicUrl>
                            <Url><![CDATA[%s]]></Url>
                      </item>
                    ";
        $item_str = "";
        $link=strval("http://mp.weixin.qq.com/s?__biz=MzIwOTM3Mjk4Nw==&mid=100000060&idx=1&sn=933396b0dbdf64cc2f19f51b0366f85c&scene=0&previewkey=B%2FR4rwNMvCyHLa61rUF8pswqSljwj2bfCUaCyDofEow%3D#wechat_redirect");
        foreach ($newsArray as $item){
            $item_str .= sprintf($itemTpl, "为什么要用易卡系统？打开了解我们", "了解易卡，了解一款帮你赚钱的收银系统","http://vip.yikant.com/Public/images/0.jpg","http://955.cc/cdzW3");
        }  
        $newsTpl = "<xml>
        <ToUserName><![CDATA[%s]]></ToUserName>
        <FromUserName><![CDATA[%s]]></FromUserName>
        <CreateTime>%s</CreateTime>
        <MsgType><![CDATA[news]]></MsgType>
        <Content><![CDATA[]]></Content>
        <ArticleCount>%s</ArticleCount>
        <Articles>
        $item_str</Articles>
        </xml>";
        $result = sprintf($newsTpl, $object->FromUserName, $object->ToUserName, time(), 1);
        return $result;
    }
}